
*** This file recreates Table 10 Panel B using recursive OOS tests
*** It generates OOS R2 and various statistics for its significance

clear

use mydata

rename *, lower

eststo clear

global ssize = _N

gen dm=mofd(date)
format dm %tm
tsset dm

* Taking lags of variables

gen l1mktrf = l1.mktrf
gen l1amihud =l1.amihud
gen l1tover = l1.tover
gen l1hml = l1.hml
gen l1smb = l1.smb
gen lsyy = l1.syy


*** cumulative returns **
gen R =0

forvalues f=0/11 {
local g = `f'+1
gen syy_1`g' = (1+R)*(1+f`f'.syy)-1 // generating holding period returns ***
replace R = syy_1`g'
}

*** critival values **

global t5 = -invt(203,0.05)
global t10 = -invt(203,0.1)


local train 120 // insample period: baseline is 120. 156 is half (13 yrs) of 27 yr sample period. 

save oss_temp, replace

matrix OOS_T=J(5,6,.)

local x = 1

foreach fvar in unlev_ma lev_ma { // constrained and uncontrained HF flows 

foreach f in 0 2 5 {

local g = `f'+1	

gen flowvar = l1.`fvar' 

local ctrlvar lsyy l1mktrf l1amihud l1tover l1hml l1smb 

matrix OOS_T[1,`x']=`g' 

local period `train'  
scalar define k = $ssize - `period' - `f' 
local y=k //the periods left for forcasting

gen yhat_a = .  // yhat of alternative model
gen yhat_n = .  // yhat of null model

forvalues i=1/`y' {

qui reg flowvar  `ctrlvar' if _n<= `period' +`i' +`f' // recursive OSS
qui predict res_flow if  _n<= `period' +`i' +`f', re  // obtain residual flows 

qui reg syy_1`g' res_flow if _n< `period' +`i'  // anomalies on residual flows here...
qui replace yhat_a=_b[_cons] + _b[res_flow]*res_flow  if _n== `period' +`i' +`f'

qui su syy_1`g' if _n< `period' +`i'
qui replace yhat_n=r(mean) if _n== `period' +`i' +`f'
drop res_flow
}

*Sqaure of Predicted error (SE)
gen se_a = (syy_1`g' - yhat_a)^2
gen se_n = (syy_1`g' - yhat_n)^2

su se_a 
scalar define MSE_A = r(mean)
su se_n 
scalar define MSE_N = r(mean)


// OSS R2
scalar define OOSR2 = (1 - MSE_A/MSE_N)*100
dis "******************Training Period is `train'*******************************"
dis "OSS-R2:  " OOSR2 
dis "***************************************************************************"
matrix OOS_T[2,`x']= OOSR2

*** Clark and Weset (2007) t-test with bootstrap
gen CW = se_n - se_a + (yhat_n - yhat_a)^2

qui reg CW , vce(bootstrap, rep(1000))
scalar define t_CW =_b[_cons]/_se[_cons]
matrix OOS_T[3,`x']= t_CW

scalar define seCW = OOSR2/t_CW
matrix OOS_T[4,`x'] = OOSR2 - seCW * $t10
matrix OOS_T[5,`x'] = OOSR2 - seCW * $t5

local ++x
use oss_temp, clear
}
}

mat rownames OOS_T = Period OOS-R2(%) OOS-T_CWbs LowB-10% LowB-5%
matrix list OOS_T, format(%9.3f)

putexcel set T10B, sheet(PanelB) modify

putexcel A1=matrix(OOS_T), names


